package com.shotnshare.app;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.NavUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.jdan.filter.BlurFilter;
import com.jdan.filter.BumpFilter;
import com.jdan.filter.ChannelMixFilter;
import com.jdan.filter.DiffuseFilter;
import com.jdan.filter.EdgeFilter;
import com.jdan.filter.EmbossFilter;
import com.jdan.filter.MaximumFilter;
import com.jdan.filter.MinimumFilter;
import com.jdan.filter.NoiseFilter;
import com.jdan.filter.PolarFilter;
import com.jdan.filter.SolarizeFilter;
import com.jdan.filter.util.AndroidUtils;

@SuppressLint("NewApi")
public class EffectScreen extends SherlockActivity {
	
	//Warning: Use layout activity_choose_img
	
	
	ImageView choosenImage;
	//the imgs to display
	Integer[] imageIDs={
			R.drawable.pic1,
			R.drawable.pic2,
			R.drawable.pic3,
			R.drawable.pic4,
			R.drawable.pic5,
			R.drawable.pic6,
			R.drawable.pic7,
			R.drawable.pic8,
			R.drawable.pic9,
			R.drawable.pic10,
			R.drawable.pic11,
			R.drawable.pic12,
			R.drawable.pic13,
			R.drawable.pic14,
			R.drawable.pic15,
			R.drawable.pic16,
	};
	
	Bitmap getImage;
	Bitmap dstImage;
	int m_CurrentEffect;
	String fileEffectPath;
	String m_CurrentPath;
	//Bitmap effect[];
	Bundle extras;
	
	private ProgressDialog mProgressDialog;
	
	private void Load_Ads() {
		
		AdView adView=null;
		if(adView == null) {
			adView = (AdView)this.findViewById(R.id.adsImage);
        }
		AdRequest ar = new AdRequest();
	   /* ar.addTestDevice(AdRequest.TEST_EMULATOR);
	    ar.addTestDevice("YT9101D530"); //Sony
	    ar.addTestDevice("HT265W507354");	
	    ar.addTestDevice("SH35JVV00526"); //Tri
	    ar.addTestDevice("323150C41B6900EC"); //Client
	    ar.addTestDevice("c1607d41105938f"); // My
	    */
	    adView.loadAd(ar);
	    
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//Action bar: add Back button
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_choose_img);
		
		m_CurrentPath ="";
		Load_Ads();
		
		extras= getIntent().getExtras();
		
		//Load image
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize=3;
		getImage=BitmapFactory.decodeFile(extras.getString("image"),options);
		dstImage=getImage;
		choosenImage=(ImageView)findViewById(R.id.choosen_image);
		choosenImage.setImageBitmap(getImage);
		

		
		/*effect = new Bitmap[16];
		effect[0]=BitmapFactory.decodeFile(extras.getString("image"),options);
		
		final ImageView choosenImage=(ImageView)findViewById(R.id.choosen_image);
		choosenImage.setImageBitmap(effect[0]);
		effect[1] = setGray(effect[0]);
		effect[2] = setSepia(effect[0]);
		effect[3] = setInvert(effect[0]);
		effect[4] = setSaturate(effect[0]);
		effect[5] = setCrystallize(effect[0]);
		effect[6] = setDiffuse(effect[0]);
		effect[7] = setNoise(effect[0]);
		effect[8] = setBumpFilter(effect[0]);
		//effect[9] = setSepia(effect[0]);
		//effect[10] = setSepia(effect[0]);*/
		
		
		Gallery gallery=(Gallery)findViewById(R.id.gallery_imgs);
		
		
		gallery.setAdapter(new ImageAdapter(this));
		gallery.setSelection(0);
		
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager wm=(WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		wm.getDefaultDisplay().getMetrics(metrics);
		
		MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
		mlp.setMargins(-((metrics.widthPixels/2)+60), 
			                 mlp.topMargin, 
			                 mlp.rightMargin, 
			                 mlp.bottomMargin
		  );	
		
		//choosenImage.setImageResource(imageIDs[(int)imageIDs.length/2]);
		gallery.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
					m_CurrentEffect = arg2;
					setSampleImage();
			}
		});
		
	}
	
	public Bitmap setEffectImage(Bitmap source, int effect){
		Bitmap dst = source;
		switch(m_CurrentEffect){
		case 1:
			dst=setGray(source);
			break;
		case 2:
			dst=setSepia(source);
			break;
		case 3:
			dst=setInvert(source);
			break;
		case 4:
			dst=setSaturate(source);
			break;
		case 5:
			dst=setSolarizeFilter(source);
			break;
		case 6:
			dst=setDiffuse(source);
			break;
		case 7:
			dst=setNoise(source);
			break;
		case 8:
			dst=setBumpFilter(source);
			break;
		case 9:
			dst=setBlur(source,8);
			break;
		case 10:
			dst=setMaxiFilter(source,2);
			break;
		case 11:
			dst=setMiniFilter(source,2);
			break;
		case 12:
			dst=setEmboss(source);
			break;
		case 13:
			dst=setEdgeFilter(source);
			break;
		case 14:
			dst=setChannelMix(source);
			break;
		case 15:
			dst=setPolarFilter(source);
			break;
		}
		return dst;
	}
	
	public void setSampleImage(){
		mProgressDialog = ProgressDialog.show(this, "", "Wait...");
        
        Thread thread = new Thread(){
            public void run() {
				dstImage = setEffectImage(getImage, m_CurrentEffect);
				final Bitmap out = dstImage;
				EffectScreen.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    	choosenImage.setImageBitmap(out);
                    }
                });
				mProgressDialog.dismiss();
            }
        };
        thread.setDaemon(true);
        thread.start();
	}
	
	public Bitmap setGray(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		//ImageSrc.getPixels(pixels, offset, stride, x, y, width, height)
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		for(int i = 0;i<w;i++){
			for(int j = 0;j<h;j++){
				int color = ImageSrc.getPixel(i, j);
				int r = (color >> 16) & 0xff;
				int g = (color >> 8) & 0xff;
				int b = color & 0xff;
				int gray = (r * 77 + g * 151 + b * 28) >> 8;
				int color2 = 0xff000000 | (gray << 16) | (gray << 8) | gray;
				
				ImageDst.setPixel(i, j, color2);
			}
		}
		return ImageDst;
	}
	
	public Bitmap setSepia(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		//ImageSrc.getPixels(pixels, offset, stride, x, y, width, height)
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		for(int i = 0;i<w;i++){
			for(int j = 0;j<h;j++){
				int color = ImageSrc.getPixel(i, j);
				int r = (color >> 16) & 0xff;
				int g = (color >> 8) & 0xff;
				int b = color & 0xff;
				int color2 = 0xff000000 + (Math.min((int)((r * 0.393) + (g * 0.769) + (b * 0.189)),255)<<16) 
						+ (Math.min((int)((r * 0.349) + (g * 0.686) + (b * 0.168)),255)<<8) 
						+ Math.min((int)((r * 0.272) + (g * 0.534) + (b * 0.131)),255);
				
				ImageDst.setPixel(i, j, color2);
			}
		}
		return ImageDst;
	}
	
	public Bitmap setInvert(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		//ImageSrc.getPixels(pixels, offset, stride, x, y, width, height)
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		for(int i = 0;i<w;i++){
			for(int j = 0;j<h;j++){
				int color = ImageSrc.getPixel(i, j);
				int color2 = 0xff000000 | (~color & 0x00ffffff);
				ImageDst.setPixel(i, j, color2);
			}
		}
		return ImageDst;
	}
	
	public Bitmap setSaturate(Bitmap ImageSrc){
		int level =3;
		    int width = ImageSrc.getWidth();
		    int height = ImageSrc.getHeight();
		    int[] pixels = new int[width * height];
		    float[] HSV = new float[3];
		    // get pixel array from source
		    ImageSrc.getPixels(pixels, 0, width, 0, 0, width, height);
		 
		    int index = 0;
		    // iteration through pixels
		    for(int y = 0; y < height; ++y) {
		        for(int x = 0; x < width; ++x) {
		            // get current index in 2D-matrix
		            index = y * width + x;
		            // convert to HSV
		            Color.colorToHSV(pixels[index], HSV);
		            // increase Saturation level
		            HSV[1] *= level;
		            HSV[1] = (float) Math.max(0.0, Math.min(HSV[1], 1.0));
		            // take color back
		            pixels[index] |= Color.HSVToColor(HSV);
		        }
		    }//
		    // output bitmap
		    Bitmap bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		    bmOut.setPixels(pixels, 0, width, 0, 0, width, height);
		    return bmOut;
	}
	
	public Bitmap setSolarizeFilter(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		SolarizeFilter filter = new SolarizeFilter();

        colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setDiffuse(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		DiffuseFilter filter = new DiffuseFilter();
        filter.setScale(3);
        colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setNoise(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		NoiseFilter filter = new NoiseFilter();
        filter.setAmount(14);
        filter.setDensity(25);
        colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setBumpFilter(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		BumpFilter filter = new BumpFilter();
		colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setBlur(Bitmap ImageSrc, int n){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		BlurFilter filter = new BlurFilter();
		for(int i=0;i<n;i++){
			colors = filter.filter(colors, w, h);
		}
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setMaxiFilter(Bitmap ImageSrc,int n){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		MaximumFilter filter = new MaximumFilter();
		for(int i=0;i<n;i++)
			colors = filter.filter(colors, w, h);
		
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setMiniFilter(Bitmap ImageSrc,int n){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		MinimumFilter filter = new MinimumFilter();
		for(int i=0;i<n;i++)
			colors = filter.filter(colors, w, h);
		
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setEmboss(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		EmbossFilter filter = new EmbossFilter();
        filter.setAzimuth(178);
        filter.setElevation(52);
        filter.setBumpHeight(98);
        colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setEdgeFilter(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		EdgeFilter filter = new EdgeFilter();
        colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setChannelMix(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		ChannelMixFilter filter = new ChannelMixFilter();
        filter.setIntoR(145);
        filter.setIntoG(125);
        filter.setIntoB(190);
        colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public Bitmap setPolarFilter(Bitmap ImageSrc){
		int w = ImageSrc.getWidth();
		int h = ImageSrc.getHeight();
		
		int colors[] = AndroidUtils.bitmapToIntArray(ImageSrc);
		PolarFilter filter = new PolarFilter();
		filter.setType(PolarFilter.RECT_TO_POLAR);
        colors = filter.filter(colors, w, h);
		Bitmap ImageDst = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888 );
		ImageDst.setPixels(colors, 0, w, 0, 0, w, h);
		
		return ImageDst;
	}
	
	public class ImageAdapter extends BaseAdapter{

		private Context ctx;
    	int imageBackground;
    	
    	public ImageAdapter(Context c) {
			ctx = c;
			TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
			imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
			ta.recycle();
		}
    	
    	@Override
    	public int getCount() {
    		
    		return imageIDs.length;
    	}

    	@Override
    	public Object getItem(int arg0) {
    		
    		return arg0;
    	}

    	@Override
    	public long getItemId(int arg0) {
    		
    		return arg0;
    	}

    	@Override
    	public View getView(int arg0, View arg1, ViewGroup arg2) {
    		ImageView iv = new ImageView(ctx);
    		iv.setImageResource(imageIDs[arg0]);
    		iv.setScaleType(ImageView.ScaleType.FIT_XY);
    		
    		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    		int width = display.getWidth(); // to get width of the screen
    		int height = display.getHeight();
    		
    		if(isTabletDevice(ctx))
    			iv.setLayoutParams(new Gallery.LayoutParams(height/5,height/5));
    		else
    			iv.setLayoutParams(new Gallery.LayoutParams(height/4,height/4));
    		iv.setBackgroundResource(imageBackground);
    		return iv;
    	}
    	public boolean isTabletDevice(Context context) {
    	    boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
    	    boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
    	    return (xlarge || large);
    	}
	}
	
	private File getOutputMediaFile(boolean saveTemp){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_PICTURES), "ShotnShare");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("ShotnShare", "failed to create directory");
                return null;
            }
        }
        if(saveTemp){
        	File mediaStor = new File("/sdcard/Android/data/", getApplicationContext().getPackageName());
        	if (! mediaStor.exists()){
                if (! mediaStor.mkdirs()){
                    Log.d("ShotnShare", "failed to create directory");
                    return null;
                }
            }
        	File mediaFile = new File(mediaStor.getPath() + File.separator + "temp_effect.jpg");
        	return mediaFile;
        }
        // Create a media file name
        if(m_CurrentPath.equals("")){
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + timeStamp + "_effect.jpg");
        m_CurrentPath = mediaFile.getPath();
        return mediaFile;
        }
        File mediaFile;
        mediaFile = new File(m_CurrentPath);
        return mediaFile;
    }
	
	public void saveFile(final boolean IsSave){
		fileEffectPath = extras.getString("image");
		if(m_CurrentEffect >0){
			mProgressDialog = ProgressDialog.show(this, "", "Saving...");
			 Context context = getApplicationContext();
				 CharSequence text = "Saved";
				 int duration = Toast.LENGTH_SHORT;
				 final Toast toast = Toast.makeText(context, text, duration);
				 toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
	       Thread thread = new Thread(){
	           public void run() {
	           	Bitmap source = BitmapFactory.decodeFile(extras.getString("image"));
	           	Bitmap destinate = setEffectImage(source,m_CurrentEffect);
	           	File pictureFile = getOutputMediaFile(!IsSave);
	           	try {
	           	       FileOutputStream out = new FileOutputStream(pictureFile);
	           	       destinate.compress(Bitmap.CompressFormat.JPEG, 90, out);
	           	       out.close();
	           	    /*EffectScreen.this.*/fileEffectPath = pictureFile.getPath();
	           	 Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	             Uri contentUri = Uri.fromFile(pictureFile);
	             mediaScanIntent.setData(contentUri);
	             EffectScreen.this.sendBroadcast(mediaScanIntent);

	           	} catch (Exception e) {
	           	       e.printStackTrace();
	           	}
	           	mProgressDialog.dismiss();
	           	//Alert saved			 
		   			 
		   			 toast.show();
		   			
	           }
	       };
		     thread.setDaemon(true);
		     thread.start();
		     
		}
		else{
			File pictureFile = new File(fileEffectPath);
			
			Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri contentUri = Uri.fromFile(pictureFile);
			mediaScanIntent.setData(contentUri);
			EffectScreen.this.sendBroadcast(mediaScanIntent);
			
			CharSequence text = "Saved";
			int duration = Toast.LENGTH_SHORT;
			final Toast toast = Toast.makeText(getBaseContext(), text, duration);
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.show();
		}
	}
	
	public void saveFile2(final boolean IsSave){
		fileEffectPath = extras.getString("image");
		if(m_CurrentEffect >0){
			//mProgressDialog = ProgressDialog.show(this, "", "Saving...");
			 Context context = getApplicationContext();
				 CharSequence text = "Saved";
				 int duration = Toast.LENGTH_SHORT;
				 final Toast toast = Toast.makeText(context, text, duration);
				 toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	       /*Thread thread = new Thread(){
	           public void run() {*/
	           	Bitmap source = BitmapFactory.decodeFile(extras.getString("image"));
	           	Bitmap destinate = setEffectImage(source,m_CurrentEffect);
	           	File pictureFile = getOutputMediaFile(!IsSave);
	           	try {
	           	       FileOutputStream out = new FileOutputStream(pictureFile);
	           	       destinate.compress(Bitmap.CompressFormat.JPEG, 90, out);
	           	       out.close();
	           	    /*EffectScreen.this.*/fileEffectPath = pictureFile.getPath();
	           	    if(IsSave){
			           	 Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			             Uri contentUri = Uri.fromFile(pictureFile);
			             mediaScanIntent.setData(contentUri);
			             EffectScreen.this.sendBroadcast(mediaScanIntent);
	           	    }
	           	} catch (Exception e) {
	           	       e.printStackTrace();
	           	}
	           	//mProgressDialog.dismiss();
	           	//Alert saved			 
		   		//	 if(IsSave)
		   		//		 toast.show();
	           /*}
	       };
		     thread.setDaemon(true);
		     thread.start();*/
		     
		}
		else{
			if(IsSave){
				File pictureFile = new File(fileEffectPath);
				
				Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
				Uri contentUri = Uri.fromFile(pictureFile);
				mediaScanIntent.setData(contentUri);
				EffectScreen.this.sendBroadcast(mediaScanIntent);
      	    }
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub		
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.activity_menu_1, menu);	
		MenuItem item=menu.findItem(R.id.menu_save);
		if(extras.getBoolean("auto_save")){
			item.setVisible(false);
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
		 switch (item.getItemId()) {
		 case android.R.id.home:  //up to previous screen:
			 if(extras.getInt("from_screen")==1){
				 NavUtils.navigateUpTo(this, new Intent(this,New_FirstScreen.class));
			 }
			 else if(extras.getInt("from_screen")==2){
				 Intent returnIntent = new Intent(this,ImageScreen.class);
				 setResult(RESULT_CANCELED, returnIntent);        
				 finish();
			 }
			 return true;	
		 case R.id.menu_save:
			 //Code save file
			 //...
			 saveFile(true);
			 //Context context = getApplicationContext();
			 //Toast.makeText(context,"Saved",Toast.LENGTH_SHORT).show();
			 break;
		 case R.id.menu_share:
			 saveFile2(extras.getBoolean("auto_save"));
			 Intent shareIntent=new Intent(this,ShareScreen.class);
			 //change file later
			 shareIntent.putExtra("afterEffect", fileEffectPath);			 
			 startActivityForResult(shareIntent, 1);			 
			 return true;
		 }
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK)
	    {
	    	 if(extras.getInt("from_screen")==1){
				 NavUtils.navigateUpTo(this, new Intent(this,New_FirstScreen.class));
			 }
	    	 else if(extras.getInt("from_screen")==2){
	    		 Intent returnIntent = new Intent(this,ImageScreen.class);
				 setResult(RESULT_CANCELED, returnIntent);        
				 finish();
			 }
	    	//moveTaskToBack(true);
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
}
